//
//  RTEmotionToolBar.swift
//  Weibo
//
//  Created by Brisinga on 16/3/14.
//  Copyright © 2016年 Root. All rights reserved.
//

import UIKit

enum RTEmotionToolBarType: Int {

    case Recent = 0, Default, Emoji, Lxh
}


protocol RTEmotionToolBarDelegate: NSObjectProtocol {

    func emotionToolBar(toolBar: RTEmotionToolBar, type: RTEmotionToolBarType)
}

class RTEmotionToolBar: UIStackView {
    
    
    // 记录上次选中的按钮
    private var lastSelectedBtn: UIButton?
    
    
    // 设置代理
    weak var delegate: RTEmotionToolBarDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        // 加载内部控件
        setupUI()
    }
    
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    // 加载内部控件
    private func setupUI() {
        
        tag = 1000
        distribution = .FillEqually
        
        addChildButtons("compose_emotion_table_left", title: "最近", type: .Recent)
        
        addChildButtons("compose_emotion_table_mid", title: "默认", type: .Default)
        
        addChildButtons("compose_emotion_table_mid", title: "Emoji", type: .Emoji)
        
        addChildButtons("compose_emotion_table_right", title: "浪小花", type: .Lxh)
    }
    
    
    // 加载子按钮
    private func addChildButtons(bgName: String, title: String, type: RTEmotionToolBarType) {
    
        let btn = UIButton(title: title, textColor: UIColor.whiteColor(), textFont: 14)
        
        // 添加按钮点击事件
        btn.addTarget(self, action: "barBtnDidClick:", forControlEvents: UIControlEvents.TouchUpInside)
        
        btn.setBackgroundImage(UIImage(named: "\(bgName)_normal"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "\(bgName)_selected"), forState: UIControlState.Selected)
        
        btn.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Selected)
        
        btn.tag = type.rawValue
        
        addArrangedSubview(btn)
    }
    
    
    
    // 选中section对应的按钮
    func selectButtonWithSection(section: Int) {
    
        let button = viewWithTag(section) as! UIButton
        
        if button == lastSelectedBtn {
            
            return
        }
        
        button.selected = true

        lastSelectedBtn?.selected = false
        
        lastSelectedBtn = button
    }
    
    
    
    
    // 按钮点击事件
    @objc private func barBtnDidClick(btn: UIButton) {
        
        
        // 如果和上一次选中按钮相同就返回
        if lastSelectedBtn == btn {
        
            return
        }
        
        
        delegate?.emotionToolBar(self, type: RTEmotionToolBarType(rawValue: btn.tag)!)
        
        lastSelectedBtn?.selected = false
        
        btn.selected = true
        
        lastSelectedBtn = btn
    }

}
